package com.mwm.loyal.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.mwm.loyal.bean.ContactBean;
import com.mwm.loyal.bean.FeedBean;
import com.mwm.loyal.bean.ResultMap;
import com.mwm.loyal.bean.UserBean;
import com.mwm.loyal.service.FeedService;
import com.mwm.loyal.service.UserService;
import com.mwm.loyal.util.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sun.net.www.protocol.ftp.FtpURLConnection;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.List;

@RestController
@RequestMapping("/mwm")
public class AndroidController {
    private ResultMap resultMap = ResultMap.getInstance();

    //第一种写法
    /*@Resource(name = "androidService")
    private BaseAndroidService androidService;*/
    //第二种写法
    @Autowired//用于实现类
    //private AndroidService androidService;
    private UserService userService;
    @Autowired//用于实现类
    private FeedService feedService;

    /**
     * 无参数表示访问根底部，如：
     * localhost:8080/mwm
     */
    @RequestMapping(value = {"", "/"})
    public ModelAndView indexRequest() {
        ModelAndView mav = new ModelAndView("index");
        mav.addObject("message", "Spring MVC!");
        return mav;
    }

    @RequestMapping("/main")
    public ModelAndView mainRequest() {
        return new ModelAndView("main");
    }

    @ResponseBody
    /*consumes： 指定处理请求的提交内容类型（Content-Type），例如application/json, text/html;
produces:    指定返回的内容类型，仅当request请求头中的(Accept)类型中包含该指定类型才返回；*/
    @RequestMapping(value = "/test", produces = "application/json; charset=utf-8")
    public String test() {
        String classesUrl = this.getClass().getResource("").getPath().replaceAll("%20", " ");
        System.out.println("classesUrl->" + classesUrl);
        String subPath = classesUrl.substring(0, classesUrl.indexOf("WEB-INF"));
        System.out.println("subPath->" + subPath);
        //获取web项目的根路径，拼接文件路径
        String filePath = subPath + "static/images/mwm.jpg";
        System.out.println("filePath->" + filePath);
        System.out.println("文件是否存在->" + new File(filePath).exists());
        return "--";
    }

    @ResponseBody
    @PostMapping(value = "/register", produces = "application/json; charset=utf-8")
    public String register(@RequestBody UserBean userBean) {
        if (null == userBean)
            return resultMap.set("-1", "数据格式错误").toJson();

        UserBean tmpBean = userService.queryUser(userBean.getUsername());
        if (null != tmpBean) {
            resultMap = resultMap.set("-1", "账号已存在");
        } else {
            String classesUrl = getClass().getResource("").getPath().replaceAll("%20", " ");
            String subPath = classesUrl.substring(0, classesUrl.indexOf("WEB-INF"));
            //获取web项目的根路径，拼接文件路径
            String filePath = subPath + "static/images/mwm.jpg";
            System.out.println("文件路径:" + filePath + "\n文件是否存在:" + new File(filePath).exists());
            byte[] bytes = StreamUtil.file2ByteArray(filePath);
            if (null != bytes)
                userBean.setIcon(bytes);
            int code = userService.register(userBean);
            resultMap = resultMap.set(String.valueOf(code), code >= 1 ? "" : "注册失败");
        }
        return resultMap.toJson();
    }

    @ResponseBody
    @PostMapping(value = "/login", produces = "application/json; charset=utf-8")
    public String login(@RequestBody UserBean userBean) {
        if (null == userBean)
            return resultMap.setError("请检查数据格式");
        try {
            UserBean resultBean = userService.login(userBean);
            if (null == resultBean) {
                resultMap.set("-1", "用户不存在或密码不正确");
            } else {
                String locked = resultBean.getLocked();
                resultMap.set("1", "");
                if (TextUtils.equals("1", locked)) {
                    resultMap = queryLock(resultBean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
        return resultMap.toJson();
    }

    @ResponseBody
    @RequestMapping(value = "/queryUser/{username}", produces = "application/json; charset=utf-8")
    public String queryUser(@PathVariable String username) {
        try {
            UserBean deviceBean = userService.getByUsername(username);
            if (null == deviceBean) {
                resultMap.set("-1", "用户名或密码不正确");
            } else {
                deviceBean.setIcon(null);
                resultMap.setCode("1").setObj(deviceBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
        return (resultMap.toJson());
    }

    @RequestMapping(value = "/showAvatar/{username}", produces = "application/json; charset=utf-8")
    public void showAvatar(@PathVariable String username) {
        try {
            /*if (TextUtils.isEmpty(username)) {
                return;
            }
            UserBean deviceBean = androidService.getByUsername(username);
            if (null == deviceBean) {
                outputStream.write(0);
            } else {
                byte[] bytes = deviceBean.getIcon();
                if (null == bytes) {
                    String realPath = request.getServletContext().getRealPath("/");
                    realPath = realPath.substring(0, realPath.lastIndexOf("target"));
                    String path = String.format("%ssrc\\main\\webapp\\static\\images\\mwm.jpg", realPath);
                    bytes = StreamUtil.file2ByteArray(path);
                }
                if (bytes == null)
                    outputStream.write(0);
                else
                    outputStream.write(bytes, 0, bytes.length);
            }
            outputStream.flush();*/
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/downloadApk")
    public void downloadApk(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"mwm.apk\"");
            DataUtil.doDownLoadApk(response);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/updateUser")
    public void updateUser(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            String json = getRequestParams(request, "beanJson");
            json = StrUtil.decodeStr2Utf(json);
            if (initParams(writer, response, json)) {
                return;
            }
            UserBean updateBean = GsonUtil.json2Bean(json, UserBean.class);
            //修改密码时用
            UserBean deviceBean;
            //不用验证原来的密码
            deviceBean = userService.getByUsername(updateBean.getUsername());
            if (null == deviceBean) {
                resultMap.set("-1", "用户名不存在");
            } else {
                int code = userService.updateAccount(updateBean);
                resultMap.set(String.valueOf(code), code == 1 ? "资料更新成功" : "更新资料失败");
            }
            writer.print(resultMap.toJson());
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/passwordUpdate")
    public void passwordUpdate(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            String json = getRequestParams(request, "beanJson");
            json = StrUtil.decodeStr2Utf(json);
            if (initParams(writer, response, json)) {
                return;
            }
            UserBean updateBean = GsonUtil.json2Bean(json, UserBean.class);
            //修改密码时用
            String oldPassword = updateBean.getNickname();
            UserBean deviceBean;
            //需要原來的密碼
            deviceBean = userService.queryUser(updateBean.getUsername());
            if (null == deviceBean) {
                resultMap.set("-1", "用户名或密码不正确");
            } else {
                int code = userService.updatePassword(updateBean);
                resultMap.set(String.valueOf(code), code == 1 ? "资料更新成功" : "更新资料失败");
            }
            writer.print(resultMap.toJson());
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/accountBindDevice")
    public void accountBindDevice(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            String username = getRequestParams(request, "username");
            if (initParams(writer, response, username)) {
                return;
            }
            UserBean deviceBean = userService.queryLock(new UserBean(username));
            if (null == deviceBean) {
                resultMap.set("-1", "用户名或密码不正确");
            } else {
                resultMap.setCode("1").setObj(deviceBean.getLocked());
            }
            writer.print(resultMap.toJson());
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/queryLocked", produces = "application/json; charset=utf-8")
    public ResultMap queryLock(UserBean tempBean) {
        UserBean deviceBean = userService.queryLock(tempBean);
        if (null == deviceBean) {
            resultMap.set("-1", "该账号不存在");
        } else {
            String lock = deviceBean.getLocked();
            if (!TextUtils.equals("1", lock)) {
                resultMap.setCode("1").setObj(deviceBean);
            } else {
                deviceBean = userService.queryLock(tempBean);
                if (null == deviceBean) {
                    resultMap.setCode("-1");
                    resultMap.setMessage("该账号已被其他设备锁定");
                } else {
                    resultMap.setCode("1");
                    resultMap.setObj(deviceBean);
                }
            }
        }
        return resultMap;
    }

    @RequestMapping("/updateAvatar")
    public void updateAvatar(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            response.setCharacterEncoding("utf-8");
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(request);
                for (FileItem item : items) {
                    String name = item.getFieldName();
                    if (item.isFormField()) {
                        String value = item.getString();
                        request.setAttribute(name, value);
                    } else {
                        String value = item.getName();
                        int start = value.lastIndexOf("\\");
                        String filename = value.substring(start + 1);
                        request.setAttribute(name, filename);
                        resultMap = DataUtil.doUpdateIcon(name, item.getInputStream());
                        writer.print(resultMap.toJson());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/updateApk")
    public void updateApk(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            response.setCharacterEncoding("utf-8");
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(request);
                FileItem item = items.get(0);
                String name = item.getFieldName();
                if (item.getSize() == 0) {
                    request.setAttribute("message", "请至少选择一个文件上传！！");
                    request.getRequestDispatcher("static/loyal/apk_upload.jsp").forward(request, response);
                    return;
                }
                if (item.isFormField()) {
                    String value = item.getString();
                    request.setAttribute(name, value);
                } else {
                    String value = item.getName();
                    int start = value.lastIndexOf("\\");
                    String filename = value.substring(start + 1);
                    request.setAttribute(name, filename);
                    String apkVer;
                    if (filename.contains("_")) {
                        apkVer = filename.substring(filename.lastIndexOf("_") + 1).replace(".apk", "");
                    } else apkVer = filename;
                    String path = request.getSession().getServletContext().getRealPath("/apk");
                    File file = new File(path, "mwm_" + apkVer + ".apk");
                    FileUtil.deleteFile(file);
                    OutputStream outs = new FileOutputStream(file);
                    int length;
                    byte[] buf = new byte[1024];
                    InputStream in = new ByteArrayInputStream(item.get());
                    while ((length = in.read(buf)) != -1) {
                        outs.write(buf, 0, length);
                    }
                    outs.flush();
                    outs.close();
                    resultMap = DataUtil.doUpdateApk(filename, apkVer, item.getInputStream());
                    String buffer = "<script>" + "parent.showProcessMessage('" + resultMap.getMessage() + "')" + "</script>";
                    writer.println(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/feedback")
    public void feedback(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            String json = getRequestParams(request, "beanJson");
            if (initParams(writer, response, json)) {
                return;
            }
            int code = feedService.feed(GsonUtil.json2Bean(json, FeedBean.class));
            writer.print(resultMap.set(String.valueOf(code), 1 == code ? "反馈成功" : "反馈失败").toJson());
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/mwmUCropTest")
    public void mwmUCropTest(HttpServletRequest request, HttpServletResponse response) {
        response.reset();
        response.setContentType("image/jpeg");
        try (PrintWriter writer = response.getWriter()) {
            response.setCharacterEncoding("utf-8");
            RequestDispatcher dis = request.getRequestDispatcher("/images/ucrop_test.jpg");
            dis.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/scan")
    public void scan(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            response.setCharacterEncoding("utf-8");
            String param = getRequestParams(request, "key");
            if (param.isEmpty()) {
                scanRequest();
            } else {
                request.setAttribute("message", "信息错误");
                request.getRequestDispatcher("/WEB-INF/page/main.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    /**
     * 生成二维码，返回到页面上
     */
    @RequestMapping("/createQrCode")
    public void createQrCode(HttpServletResponse response) {
        String url = "http://192.168.20.96:8080/mwm/apk/readme.txt";
        response.setContentType("image/jpeg");
        try (OutputStream stream = response.getOutputStream()) {
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix matrix = writer.encode(url, BarcodeFormat.QR_CODE, 256, 256);
            MatrixToImageWriter.writeToStream(matrix, "jpg", stream);
            stream.flush();
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/addContacts")
    public void addContacts(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            response.setCharacterEncoding("utf-8");
            String param = getRequestParams(request, "key");
            String beanJson = getRequestParams(request, "beanJson");
            if (param.isEmpty()) {
                writer.print("未找到此用户");
            } else {
                ContactBean contactBean = GsonUtil.json2Bean(beanJson, ContactBean.class);
                contactBean.setAccount(CipherUtil.decode(param));
                resultMap = DataUtil.doInsertContact(contactBean);
                writer.print(resultMap.toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/scanJsp")
    private ModelAndView scanRequest() {
        ModelAndView mav = new ModelAndView("scan");
        mav.addObject("message", "信息错误");
        return mav;
    }

    @RequestMapping("/checkUpdate")
    public void checkUpdate(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            resultMap.setCode("1");
            resultMap.setObj("https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk");
            writer.print(GsonUtil.obj2Json(resultMap));
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/getFeedback")
    public void getFeedback(HttpServletRequest request, HttpServletResponse response) {
        try (PrintWriter writer = response.getWriter()) {
            String username = getRequestParams(request, "username");
            if (initParams(writer, response, username)) {
                return;
            }
            List<FeedBean> beanList = feedService.queryFeed(username);
            writer.print(resultMap.setList(beanList).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/deleteFeedback")
    public void deleteFeedback(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        try (PrintWriter writer = response.getWriter()) {
            String json = getRequestParams(request, "beanJson");
            if (emptyJson(json)) {
                resultMap.set("-1", "参数不能为空");
                writer.print(resultMap.toJson());
                return;
            }
            int code = feedService.deleteFeed(GsonUtil.json2Bean(json, FeedBean.class));
            resultMap.set(String.valueOf(code), 1 == code ? "已删除" : "删除失败");
            writer.print(resultMap.toJson());
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    @RequestMapping("/accountDestroy")
    public void accountDestroy(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        try (PrintWriter writer = response.getWriter()) {
            String json = getRequestParams(request, "beanJson");
            if (emptyJson(json)) {
                writer.print(resultMap.set("-1", "参数不能为空").toJson());
                return;
            }
            UserBean deviceBean = userService.getByUsername(json);
            if (null == deviceBean)
                resultMap.set("-1", "用户名或密码不正确");
            else {
                int code = userService.destroy(deviceBean);
                resultMap.set(String.valueOf(code), 1 == code ? "删除成功" : "删除失败");
            }
            writer.print(resultMap.toJson());
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }

    private boolean initParams(PrintWriter writer, HttpServletResponse response, String json) {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (TextUtils.isEmpty(json)) {
            writer.print(resultMap.set("-1", "参数不能为空").toJson());
            return true;
        }
        return false;
    }

    private String getRequestParams(HttpServletRequest request, String param) {
        try {
            System.out.println(StrUtil.replaceNull(request.getParameter(param)));
            return StrUtil.replaceNull(request.getParameter(param));
        } catch (Exception e) {
            return "";
        }
    }

    private boolean emptyJson(String json) {
        return null == json || json.isEmpty();
    }

    @RequestMapping("/readFtp")
    public void readFtp(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("utf-8");
        try (OutputStream out = response.getOutputStream()) {
            String path = request.getParameter("url");
            FtpURLConnection connection;
            URL url;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                url = new URL(/*URLDecoder.decode(*/path/*, "utf-8")*/);
                connection = (FtpURLConnection) url.openConnection();
                connection.getInputStream(); //读取图片文件流
                int length;
                byte[] images = new byte[1024];
                while ((length = connection.getInputStream().read(images)) != -1) {
                    baos.write(images, 0, length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.write(baos.toByteArray(), 0, baos.toByteArray().length);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.setThrow(e);
        }
    }
    /*public BaseAndroidService getService() {
        return service;
    }

    public void setService(BaseAndroidService service) {
        this.service = service;
    }*/
}